//Check if the user is logged in, if not redirect to the login page
$(document).ready(function(){
    if (!checkLogin()) {
        alert("User Is Not Logged In, Redirect to Login Page.");
        window.location = '/index.html';
        return;
    }
    bindButtons();
    projectReleaseSwitch.Init();
});


// Main functions
var projectReleaseSwitch = {
    Init: function(){
        // Check admin status of user
        this.checkAdminStatus();
        // Initialize lock values
        this.initVariables();
        // New projects
        this.bindNewProjectOverlay();
        // New releases
        this.bindNewReleaseOverlay();
        // Rename projects
        this.bindRenameProjectOverlay();
        // Rename releases
        this.bindRenameReleaseOverlay();
        // Load projects
        this.loadCurrentProjects();
        // Edit users
        this.bindEditUser();
        // Highlight objects
        this.highLightAll();
        // Add projects listeners
        this.addProjectListeners();
        // Add release listeners
        this.addReleaseListeners();
        // Bind go to project release button
        this.bindGoProjectReleaseButton();
    },
    
    
    /* Initialize lock values avoiding multiple clicks, each
     button can be clicked once before closing dialogs
     */
    initVariables: function(){
        // New project button
        this.newproject_lock = false;
        // Release project button
        this.releaseproject_lock = false;
        
        lock = false;
        
    },
    
    
    // Check if the current logged in user is logged in.
    // If they are not logged in then it shouldn't show
    // any editing buttons for projects and releases.
    checkAdminStatus: function(){
    
        callApi('userApi', 'isAdmin', 'GET', {}, function(resultObj){
            if (resultObj.success == false) {
            
                $('.project-content-header-options-content').hide();
                $('.release-content-header-options-content').hide();
            }
        }, '', '', false);
    },
    
    // Bind the go project release button to 
    // redirect to the workspace if a project
    // and release is selected by the user.
    bindGoProjectReleaseButton: function(){
    
        //Listeners for the go button             
        $(".go-project-rev-btn").click(function(){
        
            // Get Project Id
            var y = $(".project-content").children(".project-content-body");
            var msg1 = jQuery.parseJSON($($(y).children(".project-name.active")[0]).find('.meta').html())
            
            // Get Release Id
            var x = $(".release-content").children(".release-content-body");
            var msg2 = jQuery.parseJSON($($(x).children(".release-name.active")[0]).find('.meta').html());
            
            // Check if user selected a project and a release
            if (msg1 == null || msg2 == null) {
                alert('You must select a project and a release!');
                return;
            }
            
            var project_id = msg1.projectId;
            var release_id = msg2.releaseId;
            
            // Redirect user to the workspace                     
            var querystring = '';
            if (project_id != '' && release_id != '') 
                querystring = '?__pid=' + project_id + '&__rid=' + release_id;
            window.location = '/workspace.html' + querystring;
        });
    },
    
    // Initialize a dialog for new projects
    bindNewProjectOverlay: function(){
        $(".new-project-overlay").dialog({
            width: 350,
            draggable: true,
            title: "New Project",
            autoOpen: false,
            closeText: "Close",
        });
    },
    
    
    // Initialize a dialog for renaming projects
    bindRenameProjectOverlay: function(){
        $(".rename-project-overlay").dialog({
            width: 350,
            draggable: true,
            title: "Rename Your Project",
            autoOpen: false,
            closeText: "Close",
        });
    },
    
    
    // Initialize a dialog for editing users' information
    bindEditUser: function(){
        $(".edit-project-overlay").dialog({
            width: 350,
            draggable: true,
            title: "Edit Users Information",
            autoOpen: false,
            closeText: "Close",
            open: function(){
            }
        })
    },
    
    
    // Initialize a dialog for creating new releases
    bindNewReleaseOverlay: function(){
        $(".new-release-overlay").dialog({
            width: 350,
            draggable: true,
            title: "New Release",
            autoOpen: false,
            closeText: "Close",
        });
    },
    
    
    // Initialize a dialog for renaming current releases
    bindRenameReleaseOverlay: function(){
        $(".rename-release-overlay").dialog({
            width: 350,
            draggable: true,
            title: "Rename your release",
            autoOpen: false,
            closeText: "Close",
        });
    },
    
    
    // Each project name box will highlight once clicked on
    highLightAll: function(){
        var t = this;
        $(".project-name").each(function(){
            $(this).click(function(){
                t.highLightElem(this);
                t.loadCurrentReleases();
                $(".release-name").each(function(){
                    $(this).click(function(){
                        t.highLightElem(this);
                    });
                });
            });
        });
    },
    
    
    // Each element will highlight once clicked on
    highLightElem: function(el){
        var previous = $(el).parent().parent().find(".active");
        previous.removeClass("active");
        $(el).addClass("active");
    },
    
    
    // Load current projects and releases
    loadCurrentProjects: function(){
    
        var param = {};
        // Show project's name
        var get_Project_Id = function(result){
            $.each(result.projects, function(key, value){
                var parameter = {
                    projectId: key
                };
                var para_encoded = JSON.stringify(parameter);
                var html_project_name = '<div class="project-name"> <div class="project-name-text">' + value + '</div><div class="meta">' + para_encoded + '</div> </div>';
                $(".project-content-body").append(html_project_name);
            })
        }
        
        // Get project's id and names from database
        callApi('projectApi', 'listProjects', 'GET', param, get_Project_Id, '', '', false);
        
        // Grab project id and release id from project url
        var input_project_id = getParameterByName('__pid');
        var input_release_id = getParameterByName('__rid');
        var t = this;
        if (input_project_id != '' && input_release_id != '') {
        
            // Highlight project
            $(".project-content-body").children(".project-name").each(function(){
                var msg = jQuery.parseJSON($(this).find('.meta').html());
                
                if (input_project_id == msg.projectId) {
                    t.highLightElem(this);
                }
            });
            
            // Show all releases associated with project and highlight release          
            t.loadCurrentReleases();
            
            
            $(".release-content-body").children(".release-name").each(function(){
                var msg = jQuery.parseJSON($(this).find('.meta').html());
                
                if (msg.releaseId == input_release_id) {
                    t.highLightElem(this);
                }
            });
            
            // Bind highlight to release names
            $(".release-name").each(function(){
                $(this).click(function(){
                    t.highLightElem(this);
                    
                });
            });
        }
    },
    // Load current releases from the database
    loadCurrentReleases: function(){
        // Remove any current releases that are displayed.
        $(".release-content-body").children(".release-name").each(function(){
            $(this).remove('.release-name');
        });
        // Get project id              
        var msg = jQuery.parseJSON($($(".project-content-body")).children(".project-name.active").find('.meta').html());
        var param = {
            projectId: msg.projectId
        }
        // Here should be revised by changing releaseID as release name    
        var callback_Release = function(result){
            for (var i in result.releases) {
                // Create new release and store its release id
                var parameter = {
                    releaseId: i
                };
                var para_encoded = JSON.stringify(parameter);
                var html_project_name = '<div class="release-name"> <div class="release-name-text">' + result.releases[i] + '</div><div class="meta">' + para_encoded + '</div> </div>';
                $(".release-content-body").append(html_project_name);
            }
        };
        // Get release from a given projectID
        callApi('projectApi', 'listReleases', 'GET', param, callback_Release, '', '', false);
    },
    
    
    // Create new projects
    addNewProjectHandler: function(el){
        var t = this;
        // Html code for new projects
        var newProjectHtml = '<div class="project-name">';
        newProjectHtml += '<div class="project-name-text"> </div>';
        newProjectHtml += '</div>';
        // Bind new projects and highlight them
        if (t.newproject_lock == false) {
            $($(".project-content-body")).prepend(newProjectHtml);
            $($($(".project-content-body")).children(".project-name")[0]).click(function(){
                t.highLightElem(this);
            });
            
            // Open a dialog
            $(".new-project-overlay").dialog("open");
            // Add new projects
            this.addNewProjectName();
            t.newproject_lock = true;
        }
    },
    
    
    // Get user's id from email address
    assignUser: function(email_result, t){
        var param = {
            "projectId": t._newProjectid,
            "users": [email_result.userId]
        };
        callApi('projectApi', 'assignUser', 'GET', param, '', '', t, true);
    },
    
    
    // Add new project button
    addNewProjectName: function(){
        var t = this;
        // Unbind previous click
        $(".ui-dialog .newproject_accept").unbind("click");
        // Unbind previous click
        $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        // Save the project name and user's email address
        $(".ui-dialog .newproject_accept").click(function(){
        
            // Project name
            var projectName = $(".ui-dialog .new-project-overlay-name input").val();
            if (projectName == "") {
                alert("Project name can not be empty");
            }
            else {
                var newprojectid = 0;
                t.setProjectId = function(project, t){
                    if (project.success == true) {
                        t._newProjectid = project.projectId;
                        newprojectid = project.projectId;
                        var parameter = {
                            projectId: t._newProjectid
                        };
                        var para_encoded = JSON.stringify(parameter);
                        var new_project_name = '<div class="project-name-text">' + projectName + '</div><div class="meta">' + para_encoded + '</div>';
                        $($(".project-content-body").children(".project-name")[0]).html(new_project_name);
                    }
                    else 
                        alert(project.message);
                }
                // Get project ID
                callApi('projectApi', 'addProject', 'GET', {
                    projName: projectName
                }, function(p, t){
                    t.setProjectId(p, t)
                }, '', t, false);
                
                var getUserInformation = function(result){
                    var param_assign = {
                        projectId: newprojectid,
                        users: [result.userId]
                    }
                    callApi('projectApi', 'assignUser', 'POST', param_assign, '', '', '', false);
                }
                callApi('userApi', 'getInfo', 'POST', '', getUserInformation, '', '', false);
                
                t.newproject_lock = false;
                // Close
                $(".new-project-overlay").dialog("close");
                // Unbind click
                $(".ui-dialog .accept").unbind("click");
                t.highLightAll();
            }
        })
        // Close
        $(".ui-dialog .ui-dialog-titlebar-close").click(function(){
            t.newproject_lock = false;
            // Remove new project.
            $($($(".project-content-body")).children(".project-name")[0]).remove();
            // Close dialog box.
            $(".new-project-overlay").dialog("close");
            // Unbind click
            $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        });
    },
    
    
    // Deletes the active release
    addDeleteProjectHandler: function(el){
        var msg = jQuery.parseJSON($($($(".project-content-body")).children(".project-name.active")[0]).find('.meta').html());
        
        // Check if a project and release is selected before removing a release
        if (msg != null) {
            var parameter = {
                projectId: msg.projectId
            };
            
            // Callback function to be executed after getting a response
            var callback = function(resultObj){
                if (resultObj.success == false) {
                    alert(resultObj.message);
                }
            }
            // Delete release from the database through an ajax call
            callApi('projectApi', 'delProject', 'POST', parameter, callback, '', '', false);
            
            // Remove html element of release
            $($(".project-name.active")[0]).remove();
        }
    },
    
    
    // Edit users information for one project
    EditProjectHandler: function(el){
        var t = this;
        // Html code for edit project-overlay
        var editProjectHtml = '<div class="edit-project">';
        editProjectHtml += '<div class="edit-project-text"> </div>';
        editProjectHtml += '</div>';
        // Bind new project so that it will highlight once clicked on
        $($(".edit-project-overlay")).prepend(editProjectHtml);
        $($($(".edit-project-overlay")).children(".edit-project")[0]).click(function(){
            t.highLightElem(this);
        });
       
        var msg = jQuery.parseJSON($($(".project-content-body")).children(".project-name.active").find('.meta').html());
        if (msg != null) {
            // Open a dialog box so that a user can input the project name.
            $(".edit-project-overlay").dialog("open");
            this.editProject(el);
            // t.newproject_lock = true;
        }
        else {
            alert("Select a project!");
        }
    },
    
    
    // Edit users information for one project
    editProject: function(el){
        var t = this;
        // Unbind previous click(s) to close.
        $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        // Unbind previous click(s) to add.
        $(".ui-dialog .editproject_add").unbind("click");
        // Unbind previous click(s) to delete.
        $(".ui-dialog .editproject_delete").unbind("click");
        // Unbind previous click(s) to save.
        $(".ui-dialog .editproject_save").unbind("click");
        
        var msg = jQuery.parseJSON($($(".project-content-body")).children(".project-name.active").find('.meta').html());
        var project_id = msg.projectId;
        param = {
            projectId: project_id
        }
        // Get user's email address
        var userid = "";
        var getuserinf = function(result){
            userid = result.userId;
        }
        // Get user's email
        callApi('userApi', 'getInfo', 'POST', '', getuserinf, '', '', false);
        var callback = function(resultObj){
            if (resultObj.success) {
                for (var i in resultObj.userIds) {
                    if (userid != resultObj.userIds[i].user_id) {
                        var parameter = {
                            userId: resultObj.userIds[i].user_id
                        }
                        var getemail = function(result){
                            if (result.success == true) {
                                $('.ui-dialog .useremail #Select1').append($("<option></option>").attr("value", 1/*key*/).text(result.email));
                            }
                            else {
                                alert("Incorrect userID");
                            }
                        }
                        callApi('userApi', 'getEmailFromUid', 'POST', parameter, getemail, '', '', false);
                    }
                };
                            };
                    }
        $('.ui-dialog .useremail #Select1 option').each(function(i, selected){
            $(selected).remove();
        });
        callApi('projectApi', 'getUsers', 'POST', param, callback, '', '', false); // to get users' email address from userID
        // Bind click to close.
        $(".ui-dialog .ui-dialog-titlebar-close").click(function(){
            // Close dialog box.
            $(".edit-project-overlay").dialog("close");
            // Unbind click to close.
            $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        });
        
        
        
        //Bind click to add
        $(".ui-dialog .editproject_add").click(function(){
            // Get email name
            var newuseremail = $(".ui-dialog .edit-project-overlay-email input").val();
            var callback = function(resultObj){
                if (resultObj.success) {
                    userID = resultObj.userId;
                }
            }
            callApi('userApi', 'getUidFromEmail', 'POST', {
                email: newuseremail
            }, callback, '', '', false);
            
            var assignNewProject = function(assign_result){
                if (assign_result.success == false) {
                    alert("Email address is not assigned, enter a correct one!");
                }
                else {
                    $('.ui-dialog .useremail #Select1').append($("<option></option>").attr("value", 1/*key*/).text(newuseremail));
                }
            }
            projectID = project_id;
            param = {
                projectId: projectID,
                users: [userID]
            }
            callApi('projectApi', 'assignUser', 'POST', param, assignNewProject, '', '', false);
        });
        
        
        //Bind click to delete
        $(".ui-dialog .editproject_delete").click(function(){
            // Get project name
            $('.ui-dialog .useremail #Select1 :selected').each(function(i, selected){
                // remove from the database
                // to get the user's ID from email address
                
                var callback = function(resultObj){
                    if (resultObj.success) {
                        userID = resultObj.userId;
                        //alert(resultObj.userId);
                    }
                }
                
                callApi('userApi', 'getUidFromEmail', 'POST', {
                    email: $(selected).text()
                }, callback, '', '', false);
                
                projectID = project_id;
                
                param = {
                    projectId: projectID,
                    users: [userID]
                }
                
                callApi('projectApi', 'dissociateUsers', 'POST', param, '', '', '', false);
                
                
                $(selected).remove();
            });
        });
        
        // Bind click to save
        $(".ui-dialog .editproject_close").click(function(){
            // Close dialog box.
            $(".edit-project-overlay").dialog("close");
            // Unbind click to close.
            $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        });
        
    },
    
    
    // Listen for a new project button
    addProjectListeners: function(){
        var t = this;
        $(".project-new").click(function(){
            t.addNewProjectHandler();
        });
        // Listen for a delete project button
        $(".project-delete").click(function(){
            t.addDeleteProjectHandler();
        });
        // Listen for rename project button
        $(".project-rename").click(function(){
            t.renameProjectHandler();
        });
        // Listen for edit project button
        $(".project-edit-users").click(function(){
            t.EditProjectHandler();
        });
    },
    
    
    // Creates a new release at the top of the list
    addNewReleaseHandler: function(){
        var t = this;
        // Html code for new release
        var newProjectHtml = '<div class="release-name">';
        newProjectHtml += '<div class="release-name-text"> </div>';
        newProjectHtml += '</div>';
        // Bind new release so that it will highlight once clicked on
        var msg = jQuery.parseJSON($($(".project-content-body")).children(".project-name.active").find('.meta').html());
        
        if (t.releaseproject_lock == false && msg != null) {
            $($(".release-content-body")).prepend(newProjectHtml);
            $($(".release-name")[0]).click(function(){
                t.highLightElem(this);
            });
            // Open a dialog box so that a user can input the release name.
            $(".new-release-overlay").dialog("open");
            // Add the new release to the list of current releases
            this.addNewReleaseName();
            t.releaseproject_lock = true;
        }
    },
    
    
    addNewReleaseName: function(){
        var t = this;
        // Unbind previous click(s) to accept.
        $(".ui-dialog .accept").unbind("click");
        // Unbind previous click(s) to close.
        $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        // Bind click to accept.
        $(".ui-dialog .accept").click(function(){
            t.releaseproject_lock = false;
            // Get project name
            var name = '<div class="release-name-text">' + $(".ui-dialog .new-release-overlay-name input").val() + '</div>';
            // Replace release with project containing input name
            $($($(".release-content-body")).children(".release-name")[0]).removeClass("release-name-text");
            $($($(".release-content-body")).children(".release-name")[0]).html(name);
            
            var y = $(".project-content-body");
            var msg = jQuery.parseJSON($(y).children(".project-name.active").find('.meta').html());
            var project_id = msg.projectId;
            
            
            projectID = project_id;
            param = {
                projectId: projectID,
                name: $(".ui-dialog .new-release-overlay-name input").val()
            }
            
            callApi('projectApi', 'addRelease', 'POST', param, '', '', '', false);
            
            // Load current release so that a new release has an id stored.
            t.loadCurrentReleases();
            
            $(".release-name").each(function(){
                $(this).click(function(){
                    t.highLightElem(this);
                });
            });
            
            // Close dialog box
            $(".new-release-overlay").dialog("close");
            // Unbind click to accept
            $(".ui-dialog .accept").unbind("click");
        });
        
        // Bind click to close
        $(".ui-dialog .ui-dialog-titlebar-close").click(function(){
            t.releaseproject_lock = false;
            // Remove new project
            $($($(".release-content-body")).children(".release-name")[0]).remove();
            // Close dialog box.
            $(".new-release-overlay").dialog("close");
            // Unbind click to close.
            $(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
        });
    },
    
    
    // Open a dialog that allows the user to rename a project.
    renameProjectHandler: function(){
       
        // Rename the highlighted project.
        this.renameProject();
    },
    
    
    // Open a dialog that allows the user to rename a release.
    renameReleaseHandler: function(){
    
        // Rename the highlighted release.
        this.renameRelease();
    },
    
    
    renameRelease: function(){
    
        var t = this;
		
		// Check if a release is selected before allowing to rename
        if ($(".release-content-body").find(".active").length) {
			
			$(".rename-release-overlay").dialog("open");
			
			// Unbind previous click(s) to accept.  
			$(".ui-dialog .accept").unbind("click");
			
			// Unbind previous click(s) to close.
			$(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
		
			// Bind click to accept.
			$(".ui-dialog .accept").click(function(){
			
				// Get the edited project name from user.
				var newReleaseName = $(".ui-dialog .rename-release-overlay-name input").val();
				var name = '<div class="release-name-text">' + newReleaseName + '</div>';
				
				// Replace release with project containing input name
				var msg = jQuery.parseJSON($($(".release-content-body")).children(".release-name.active").find('.meta').html());
				$(".release-name.active").removeClass("release-name-text");
				$(".release-name.active").html(name);
				
				var param = {
					"releaseId": msg.releaseId,
					"name": newReleaseName
				};
				
				// This function fires after the ajax call returns
				var callback = function(resultObj){
					if (resultObj.success) {
					//alert('Change Release Sucess!');
					}
					else {
						alert('Change Release Fail!');
					}
				}
				
				callApi('projectApi', 'renameRelease', 'POST', param, callback, '', '', false);
				
				// Close dialog box
				$(".rename-release-overlay").dialog("close");
				
				// Unbind previous click to accept.
				$(".ui-dialog .accept").unbind("click");
			});
			
			// Bind click to close
			$(".ui-dialog .ui-dialog-titlebar-close").click(function(){
				t.releaseproject_lock = false;
				// Close dialog box.
				$(".rename-release-overlay").dialog("close");
				// Unbind click to close.
				$(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
			});
		}
    },
    
    // renaming project button
    renameProject: function(){
		
		// Check if there is a project selected
		if ($(".project-content-body").find(".active").length) {
			
			$(".rename-project-overlay").dialog("open");
			
			// Unbind previous click(s) to accept.  
			$(".ui-dialog .accept").unbind("click");
			
			// Unbind previous click(s) to close.
			$(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
			
			// Bind click to accept.
			$(".ui-dialog .accept").click(function(){
				
				// Get the edited project name from user.
				var newname = $(".ui-dialog .rename-project-overlay-name input").val();
				// Replace project with project containing input name
				var oldname = $($(".project-content-body")).children(".project-name.active").text();
				$(".project-name.active").children('.project-name-text').html($(".ui-dialog .rename-project-overlay-name input").val());
				var msg = jQuery.parseJSON($(".project-name.active").find('.meta').html());
				
				var param = {
					"projectId": msg.projectId, //here should be revised
					"projName": newname
				};
				// This function fires after the ajax call returns
				var callback = function(resultObj){
					if (resultObj.success == false) {
						alert(resultObj.message);
					}
				}
				callApi('projectApi', 'renameProject', 'POST', param, callback, '', '', false);
				// Close dialog box
				$(".rename-project-overlay").dialog("close");
				// Unbind previous click to accept
				$(".ui-dialog .accept").unbind("click");
				
			});
			
			$(".ui-dialog .ui-dialog-titlebar-close").click(function(){
				// Close dialog box.
				$(".rename-project-overlay").dialog("close");
				// Unbind click to close.
				$(".ui-dialog .ui-dialog-titlebar-close").unbind("click");
			});
		}
    },
    
    
    // Deletes the active release
    addDeleteReleaseHandler: function(){
    
        // Get release ID
        var msg = jQuery.parseJSON($($($(".release-content-body")).children(".release-name.active")[0]).find('.meta').html());
        
        // Check if a project and release is selected before removing a release
        if (msg != null) {
            var parameter = {
                release_id: msg.releaseId
            };
            
            // Callback function to be executed after getting a response
            var callback = function(resultObj){
                if (resultObj.success == true) {
                    //alert("success");
                }
                else 
                    alert("failed to delete release")
            }
            // Delete release from the database through an ajax call
            callApi('projectApi', 'delRelease', 'POST', parameter, callback, '', '', false);
            
            // Remove html element of release
            $($(".release-name.active")[0]).remove();
        }
    },
    
    
    // Add release listeners
    addReleaseListeners: function(){
        var t = this;
        //Listener for the new button of release
        $(".release-new").click(function(){
            t.addNewReleaseHandler();
        });
        //Listener for the delete button of release
        $(".release-delete").click(function(){
            t.addDeleteReleaseHandler();
        });
        //Listener for the rename button of release
        $(".release-rename").click(function(){
            t.renameReleaseHandler();
        });
    }
}